<template>
  <div class="project-management">
    <div class="card">
      <div class="card-header flex-between">
        <span>项目列表</span>
        <button @click="showAddModal = true" class="btn">+ 添加项目</button>
      </div>

      <div v-if="loading" class="text-center p-2">
        <div class="loading"></div>
      </div>

      <table v-else>
        <thead>
          <tr>
            <th>项目名称</th>
            <th>项目描述</th>
            <th>主机数量</th>
            <th>创建时间</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="project in projects" :key="project.id">
            <td>{{ project.name }}</td>
            <td>{{ project.description || '-' }}</td>
            <td>{{ project.host_count }}</td>
            <td>{{ formatDate(project.created_at) }}</td>
            <td>
              <div class="flex gap-1">
                <button @click="editProject(project)" class="btn" style="padding: 4px 8px; font-size: 10px;">编辑</button>
                <button @click="deleteProject(project.id)" class="btn btn-danger" style="padding: 4px 8px; font-size: 10px;">删除</button>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- Add/Edit Modal -->
    <div v-if="showAddModal || showEditModal" class="modal" @click.self="closeModal">
      <div class="modal-content">
        <div class="modal-header">
          <h2>{{ showEditModal ? '编辑项目' : '添加项目' }}</h2>
          <button @click="closeModal" class="modal-close">✕</button>
        </div>
        <div class="modal-body">
          <form @submit.prevent="saveProject">
            <div class="form-group">
              <label>项目名称 *</label>
              <input v-model="formData.name" type="text" required />
            </div>
            <div class="form-group">
              <label>项目描述</label>
              <textarea v-model="formData.description" rows="4"></textarea>
            </div>
            <div class="flex gap-1 mt-2">
              <button type="submit" class="btn">保存</button>
              <button type="button" @click="closeModal" class="btn btn-danger">取消</button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import api from '../services/api'

const projects = ref([])
const loading = ref(false)
const showAddModal = ref(false)
const showEditModal = ref(false)

const formData = ref({
  name: '',
  description: ''
})

onMounted(() => {
  fetchProjects()
})

const fetchProjects = async () => {
  loading.value = true
  try {
    const response = await api.getProjects()
    projects.value = response.results || response
  } catch (error) {
    console.error('Failed to fetch projects:', error)
  } finally {
    loading.value = false
  }
}

const editProject = (project) => {
  formData.value = { ...project }
  showEditModal.value = true
}

const saveProject = async () => {
  try {
    if (showEditModal.value) {
      await api.updateProject(formData.value.id, formData.value)
    } else {
      await api.createProject(formData.value)
    }
    await fetchProjects()
    closeModal()
  } catch (error) {
    console.error('Failed to save project:', error)
    alert('保存失败: ' + (error.response?.data?.detail || error.message))
  }
}

const deleteProject = async (id) => {
  if (!confirm('确定要删除这个项目吗?')) return
  try {
    await api.deleteProject(id)
    await fetchProjects()
  } catch (error) {
    console.error('Failed to delete project:', error)
    alert('删除失败: ' + (error.response?.data?.detail || error.message))
  }
}

const closeModal = () => {
  showAddModal.value = false
  showEditModal.value = false
  formData.value = { name: '', description: '' }
}

const formatDate = (dateString) => {
  return new Date(dateString).toLocaleString('zh-CN')
}
</script>

<style scoped>
.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: var(--color-bg-secondary);
  border: 2px solid var(--color-accent-cyan);
  border-radius: 8px;
  width: 90%;
  max-width: 600px;
  max-height: 90vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 2px solid var(--color-border);
}

.modal-header h2 {
  color: var(--color-accent-cyan);
  text-transform: uppercase;
  letter-spacing: 2px;
  font-size: 18px;
}

.modal-close {
  background: transparent;
  border: none;
  color: var(--color-accent-red);
  font-size: 24px;
  cursor: pointer;
}

.modal-body {
  padding: 20px;
}
</style>
